package com.rr.security.filter;

import com.rr.security.AuthTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author RR
 * @date 2023/3/14 13:09
 */
/*
 * 自定义的登录验证授权过滤器
 * */
public class MyLoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthTokenManager authTokenManager;
    private AuthenticationManager authenticationManager;

    public MyLoginAuthenticationFilter(AuthenticationManager authenticationManager, AuthTokenManager authTokenManager) {
        this.authenticationManager = authenticationManager;
        this.authTokenManager = authTokenManager;
        this.setPostOnly(false);
        super.setAuthenticationManager(authenticationManager);
        // 重点，需要设置登录的url，否则不会拦截到
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/user/doLogin", "POST"));
    }

    // 可自定义接收前端提交的登录信息，然后进行验证登录
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    // 登录成功后自定义操作，比如生成token
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String username = request.getParameter("username");
        String token = authTokenManager.addToken(username);
        System.out.println("保存token:" + token);
        chain.doFilter(request, response);
    }

    // 自定义登录失败操作内容
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);
    }


}
